//
//  MainViewController.swift
//  LX_weibo
//
//  Created by LTT❤️ on 15/6/24.
//  Copyright © 2015年 LTT. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tb = MainTabBar()
        
        setValue(tb, forKeyPath: "tabBar")
        tb.compoesButton.addTarget(self, action: "composeButtonClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
         addChildViewControllers()

        // Do any additional setup after loading the view.
    }
    
    func composeButtonClicked(){
        print(__FUNCTION__)
    }
    
    
    private func addChildViewControllers() {
        //加载json
        let path = NSBundle.mainBundle().pathForResource("MainVCSettings.json", ofType: nil)!
        let data = NSData(contentsOfFile: path)!
        
        //反序列化  后面有throw的都要用这种写法
        do{
         let array = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
            
            //指明字典种的类型
            for dict in array as! [[String:String]]{
                print(dict)
                addChildViewController(dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!)
            }
            
        }catch{
          print(error)
        }

    }

    private func addChildViewController(vcName:String,title:String,imageName:String) {
    
        
       let ns = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"]as!String
        let cls :AnyClass =  NSClassFromString(ns+"."+vcName)!
        
        
        let vc = cls.new()as! UIViewController
        
        
        
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName+"_highlighted")
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }
    
    
    

}
